package com.itbac.j2cache.rabbitmq.constants;

import sun.management.VMManagement;

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @description 获取进程 PID ，做 MQ 的 queue name，表示当前节点。
 *
 * @author itbac
 * @email 1218585258@qq.com
 * @date 2020/6/17
 */
public class RabbitMQQueuesNameByJvmPid {
    //动态队列名
    private static String name;

    public static String getName() {
        return name;
    }


    static {
        name = QueueName.QUEUE_NAME_PREFIX+ jvmPid();
    }

    public static final int jvmPid() {
        try {
            RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
            Field jvm = runtime.getClass().getDeclaredField("jvm");
            jvm.setAccessible(true);
            VMManagement mgmt = (VMManagement) jvm.get(runtime);
            Method pidMethod = mgmt.getClass().getDeclaredMethod("getProcessId");
            pidMethod.setAccessible(true);
            int pid = (Integer) pidMethod.invoke(mgmt);
            System.out.println("RabbitMQQueuesNameByJvmPid.jvmPid:"+pid);
            return pid;
        } catch (Exception e) {
            return -1;
        }
    }
}
